<template>
	<view>
		<view class="touxiang-div"><image class="touxiang" :src="touxiang" @tap="uploade()"></image></view>
	    <button class="big-btn" @tap="save()">确定</button>
	</view>
	
</template>

<script>
import httpPath from '@/static/js/path.js';
import { getlogin } from '@/static/js/login.js';
export default {
	data() {
		return {
			userinfo: {},
			wxinfo_id: '',
			touxiang:"",
			imgid:"",
			path:"",
		};
	},

	onPageScroll(e) {
		//兼容iOS端下拉时顶部漂移
		this.headerPosition = e.scrollTop >= 0 ? 'fixed' : 'absolute';
		this.headerTop = e.scrollTop >= 0 ? null : 0;
		this.statusTop = e.scrollTop >= 0 ? null : -this.statusHeight + 'px';
	},
	onLoad(option) {
		this.userinfo = getlogin();
		this.wxinfo_id = this.userinfo.wxinfo_id;
		this.touxiang = this.userinfo.head_url;
		if(option.avatar){
			this.path=option.avatar;
			this.uptouxiang();
		}
	},

	methods: {
		uptouxiang(){
			let $this=this;
			wx.uploadFile({
				url: httpPath.filePath + '/index/common/upload_m', //仅为示例，非真实的接口地址
				filePath: this.path,
				name: 'img',
				formData: {
					user: 'test'
				},
				success(res) {
					console.log(res);
					let data = JSON.parse(res.data);
					$this.touxiang=httpPath.filePath + data.msg;
					$this.path= data.msg;
					$this.id=data.id;
				}
			})
		},
		uploade() {
			let $this = this;
			wx.chooseImage({
				count: 1, //默认9
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album', 'camera'],
				success: function(res) {
					uni.redirectTo({
						url: 'upload?src=' + res.tempFilePaths[0]
					});
					
				},
			})
		},
		/**
		 * 保存头像
		 */
		save(){
			if(!this.path){
				uni.showModal({
					showCancel: false,
					content:"请上传头像"
				})
				return false;
			}
			uni.request({
				url: httpPath.filePath+'/index/wxinfo/head',
				method:'POST',
				header:{'content-type':'application/x-www-form-urlencoded'},
				data: {wxinfo_id:this.wxinfo_id,filepath:this.path},
				success: (res) => {
					if(res.data.code==200){
						this.userinfo.head_url=res.data.data.filepath;
						uni.setStorage({
						    key: 'user',
						    data: this.userinfo,
						    success: function () {
						       uni.navigateBack()
						    }
						});
					}  
				}
			});
		}
	}
};
</script>

<style>
.touxiang-div {
	width: 500rpx;
	height: 500rpx;
	margin: auto;
	padding-top: 20%;
}
.touxiang {
	width: 500rpx;
	height: 500rpx;
	
}
.big-btn{position: fixed;bottom: 150rpx;left: calc(50% - 265rpx);}
</style>
